package com.itzhanghada.rebitmq.Controller;

import com.itzhanghada.rebitmq.domin.vo.TransactionRecord;
import com.itzhanghada.rebitmq.enums.TransactionStatus;
import com.itzhanghada.rebitmq.redis.RedisStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/rebit-mq/admin")
public class AdminController {
    
    @Autowired
    private RedisStorageService storageService;
    
    @GetMapping("/transactions")
    public List<TransactionRecord> getTransactions(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String serviceName,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        // 实现分页查询事务记录
        // 实际实现需要根据需求从Redis中查询和过滤
        return Collections.emptyList();
    }
    
    @GetMapping("/transactions/{txId}")
    public TransactionRecord getTransaction(@PathVariable String txId) {
        return storageService.getTransactionRecord(txId);
    }
    
    @PostMapping("/transactions/{txId}/retry")
    public ResponseEntity<String> retryTransaction(@PathVariable String txId) {
        TransactionRecord record = storageService.getTransactionRecord(txId);
        if (record == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 手动重试
        storageService.updateTransactionStatus(txId, TransactionStatus.RETRYING);
        
        return ResponseEntity.ok("Retry initiated");
    }
    
    @PostMapping("/transactions/{txId}/cancel")
    public ResponseEntity<String> cancelTransaction(@PathVariable String txId) {
        TransactionRecord record = storageService.getTransactionRecord(txId);
        if (record == null) {
            return ResponseEntity.notFound().build();
        }
        
        // 取消事务
        storageService.updateTransactionStatus(txId, TransactionStatus.FAILED);
        
        return ResponseEntity.ok("Transaction cancelled");
    }
    
    @GetMapping("/metrics")
    public Map<String, Object> getMetrics() {
        // 返回各种监控指标
        Map<String, Object> metrics = new HashMap<>();
        // 实现指标收集逻辑
        return metrics;
    }
}